package com.flw.controller.user;

import com.flw.entity.User;
import com.flw.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 本类用于:用户业务逻辑层的实现类
 *
 * @author Bruce
 * @version v1.0
 * @create 2017-07-24 10:06
 **/

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/backLoginEdit")
    public String backLoginEdit(){
        return "user/backLoginEdit";
    }

    //后台验证登录
    @RequestMapping("/backLogin")
    public String backLogin(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session, String userNum, String password, String check) throws UnsupportedEncodingException {
        User user = userService.findByUserNum(userNum);
        System.out.println("用户编号:"+userNum);
        System.out.println("密码："+password);
        System.out.println("打印请记住我"+check);

        model.addAttribute("userNum",userNum);
        model.addAttribute("password",password);
        model.addAttribute("check",check);

        if(userNum == null || userNum.trim().length()<1){
            model.addAttribute("userNumErr","用户名不能为空");
            System.out.println("用户名不能为空");
            return "/user/backLoginEdit";
        }else if (user ==null){
            model.addAttribute("userNumErr","用户名不存在");
            System.out.println("用户名不存在");
            return "/user/backLoginEdit";
        }else if(password ==null || password.trim().length()<1){
            model.addAttribute("userPasswordErr","密码不能为空");
            System.out.println("密码不能为空");
            return "/user/backLoginEdit";
        }else if(!user.getPassword().equals(password)){
            model.addAttribute("userPasswordErr","密码错误");
            System.out.println("密码错误");
            return "/user/backLoginEdit";
        }
        if(check != null){
            //说明勾选了记住密码,如果勾选了,但是该控件没有提供value属性的值,那么默认是on,否则是null
            //创建Cookie对象

            //为了防止用户名出现中文,所以需要对用户名进行一级编码
            String uNum = URLEncoder.encode(userNum,"utf-8");

            Cookie cookie = new Cookie("userNum",uNum+":"+password);

            //设置过期时间为一周,单位是秒
            cookie.setMaxAge(60*60*24*7);

            //设置cookie可访问路径[整个应用都有效]
            cookie.setPath("/");
            System.out.println("用户名存入Cookie");
            //将cookie写入到客户端
            response.addCookie(cookie);
        }else {
            Cookie[] cookies = request.getCookies();
            if(null!=cookies && cookies.length>0){
                for (Cookie c : cookies) {
                    if("userNum".equals(c.getName())){
                        //Cookie cc = new Cookie("username",null);
                        c.setValue(null);
                        ////设置该cookie的过期时间.
                        c.setMaxAge(1);

                        c.setPath("/");
                        System.out.println("删除Cookie");
                        response.addCookie(c);
                    }
                }
            }
        }
        //TODO 可以做输错三次密码锁定

        //将找到的用户存到Session作用域中
        session.setAttribute("user",user);
        return "forward:/movie/list";
    }

    //后台跳转到注册页面
    @RequestMapping("/backRegisterEdit")
    public String backRegisterEdit(){
        return "user/backRegisterEdit";
    }

    //后台注册
    @RequestMapping("/backRegister")
    public String backRegister(Model model, User user, String pwd1){
        System.out.println("========进入注册后台=========");
        System.out.println("打印User: "+user);
        System.out.println("打印手机号:"+user.getPhone());

        //将用户名和密码存到作用域中方便登录可以不用输入
        model.addAttribute("user",user);

        if(user == null){
            model.addAttribute("userErr","您可能没有输入有效信息");
            return "user/backRegisterEdit";

        }else if(user.getUserNum() ==null || user.getUserNum().trim().length()<1){
            model.addAttribute("userNumErr","用户名不能为空");
            return "user/backRegisterEdit";

        }else if(userService.findByUserNum(user.getUserNum()) != null){
            model.addAttribute("userNumErr","用户名已存在");
            return "user/backRegisterEdit";

        }
        if(user.getUserName() == null || user.getUserName().trim().length()<1){
            //如果用户没有输入昵称，则统一为“新注册会员”
            user.setUserName("新注册会员");
//          return "user/backRegisterEdit";

        }
        if(user.getPassword() == null || user.getPassword().trim().length()<1){
            model.addAttribute("passwordErr","密码不能为空");
            System.out.println("密码不能为空");
            return "user/backRegisterEdit";

        }else if(!user.getPassword().equals(pwd1)){
            model.addAttribute("password1Err","两次密码输入不一致");
            return "user/backRegisterEdit";

        }else if(user.getEmail() ==null || user.getEmail().trim().length()<1){
            model.addAttribute("emailErr","邮箱不能为空");
            return "user/backRegisterEdit";

        }else if(!user.getEmail().matches("^[A-Za-z0-9]+@[A-Za-z0-9]+[-.]+[A-Za-z]+$")){
            model.addAttribute("emailErr","邮箱格式不正确");
            return "user/backRegisterEdit";
        }else if(user.getPhone() == null || !user.getPhone().matches("^1[3|4|5|7|8][0-9]{9}$")){
            model.addAttribute("phoneErr","电话号码格式不正确");
            return "user/backRegisterEdit";
        }
        user.setRegisterDate(new Date());
        userService.save(user);

        //存入作用域，方便登录
        model.addAttribute("userNum",user.getUserNum());
        model.addAttribute("password",user.getPassword());

        return "user/backLoginEdit";
    }

    //模态框登录
    @RequestMapping("/modelLogin")
    public String modelLogin(HttpSession session, String flag, HttpServletRequest req, HttpServletResponse resp, String userNum, String password) throws IOException, IOException {
        System.out.println("记住信息：" + flag);
        PrintWriter out = resp.getWriter();
        /*
        System.out.println("用户名：" + userNum);
        System.out.println("密码：" + password);
        System.out.println("++++=======进入model登录验证=========++");*/

        //根据userNum来获取user
        User user = userService.findByUserNum(userNum);
        System.out.println(user);
        if (user == null) {
            //0 代表用户不存在
            out.print("0");
           /* System.out.print("用户不存在");*/
            return null;
        } else if (!password.equals(user.getPassword())) {
            //1 代表密码错误
            out.print("1");
           /* System.out.print("密码错误");*/
            return null;
        }
        session.setAttribute("user", user);
        if (flag != null) {
            //说明勾选了记住密码,如果勾选了,但是该控件没有提供value属性的值,那么默认是on,否则是null
            //创建Cookie对象

            //为了防止用户名出现中文,所以需要对用户名进行一级编码
            String uname = URLEncoder.encode(userNum, "utf-8");

            Cookie cookie = new Cookie("userNum", uname + ":" + password);

            //设置过期时间为一周,单位是秒
            cookie.setMaxAge(60 * 60 * 24 * 7);

            //设置cookie可访问路径[整个应用都有效]
            cookie.setPath("/");

            //将cookie写入到客户端
            resp.addCookie(cookie);

        } else {
            Cookie[] cookies = req.getCookies();
            if (null != cookies && cookies.length > 0) {
                for (Cookie c : cookies) {
                    if ("userNum".equals(c.getName())) {
                        //Cookie cc = new Cookie("username",null);
                        c.setValue(null);
                        ////设置该cookie的过期时间.
                        c.setMaxAge(1);

                        c.setPath("/");

                        resp.addCookie(c);
                    }
                }
            }

        }
        return "redirect:/movie/list";
    }

    @RequestMapping("/modelRegisterCheckUser")
    public void modelRegisterCheckUser(String userNum, HttpServletResponse response) throws IOException {
        /*System.out.println("进入注册验证后台....................");*/

        PrintWriter out = response.getWriter();
        User user = userService.findByUserNum(userNum);

        System.out.println("打印传过来的userNum: "+userNum);
        System.out.println("打印找到的User: "+user);

        if(user !=null ){
            // 1 - 代表用户存在
            out.print("1");
        }else {
            // 0 - 代表用户不存在
            out.print("0");
        }
    }


    //模态框注册
    @RequestMapping("/modelRegister")
    public String modelRegister(Model model,User user) {
        System.out.println("++++:"+user.getPhone());
        /*System.out.println("进入保存数据后台....................");*/
        model.addAttribute("user",user);
        user.setRegisterDate(new Date());
        userService.save(user);
        model.addAttribute("model_login","show");
        return "redirect:/movie/list";
    }

    //安全退出
    @RequestMapping("safeExit")
    public String safeExit(HttpSession session){
        //清除Session数据
        session.invalidate();
        //返回主页面
        return "redirect:/movie/list";
    }
}
